package com.isyscore.os.metadata.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.isyscore.device.common.model.RespDTO;
import com.isyscore.os.metadata.enums.KettleJobTriggerType;
import com.isyscore.os.metadata.kettle.dto.FlowTaskDTO;
import com.isyscore.os.metadata.kettle.dto.FlowTaskPageReqDTO;
import com.isyscore.os.metadata.service.DataFlowDefinitionService;
import com.isyscore.os.metadata.service.DataFlowTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("${api-full-prefix}/etlflow/task")
@Api(tags = "ETL流程任务实例")
@Slf4j
@RequiredArgsConstructor
public class ETLFlowTaskController {

    private final DataFlowTaskService dataFlowTaskService;
    private final DataFlowDefinitionService dataFlowDefinitionService;
    @ApiOperation("异步启动一个新的ETL流程任务")
    @PostMapping("/start/{definitionId}")
    public RespDTO<String> runTask(@ApiParam(name = "definitionId", value = "流程定义ID", required = true) @PathVariable("definitionId") String definitionId,
                                   @ApiParam(name = "params", value = "启动任务时的动态参数", required = false) @RequestBody(required = false) Map<String, String> params) {

        return RespDTO.onSuc(dataFlowTaskService.runTask(definitionId,params, KettleJobTriggerType.MANUAL,null));
    }


    @ApiOperation("查看某个任务实例详情")
    @GetMapping("/{id}")
    public RespDTO<FlowTaskDTO> detail(@ApiParam(name = "id", value = "任务实例ID", required = true) @PathVariable("id") String id) {
        return RespDTO.onSuc(dataFlowTaskService.getFlowTask(id));
    }

    @ApiOperation("分页查询任务实例")
    @GetMapping("/page")
    public RespDTO<IPage<FlowTaskDTO>> page(FlowTaskPageReqDTO req) {
        return RespDTO.onSuc(dataFlowTaskService.page(req));
    }

    @ApiOperation("获得运行中的流程")
    @GetMapping("/runningFlows")
    public RespDTO<List<String>> runningFlows() {
        return RespDTO.onSuc(dataFlowTaskService.runningFlows());
    }

    @ApiOperation("停止运行中的任务")
    @GetMapping("/stopTask/{taskId}")
    public RespDTO<String> killTask(@PathVariable("taskId") String taskId) {
        dataFlowTaskService.stopTask(taskId);
        return RespDTO.onSuc();
    }

    @ApiOperation("获取任务运行状态")
    @GetMapping("/status/{taskId}")
    public RespDTO<String> status(@PathVariable("taskId") String taskId) {
        return RespDTO.onSuc( dataFlowTaskService.taskStatus(taskId));
    }
}
